package com.lzxuni.modules.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzxuni.modules.common.entity.PageParameter;
import com.lzxuni.modules.organization.entity.Authorize;
import com.lzxuni.modules.organization.entity.Role;
import com.lzxuni.modules.organization.entity.User;
import com.lzxuni.modules.organization.entity.UserRelation;
import com.lzxuni.modules.organization.mapper.RoleMapper;
import com.lzxuni.modules.organization.service.AuthorizeService;
import com.lzxuni.modules.organization.service.RoleService;
import com.lzxuni.modules.organization.service.UserRelationService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author 孙志强
 * @since 2018-12-07
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
	@Autowired
	private UserRelationService userRelationService;
	@Autowired
	private AuthorizeService authorizeService;

	@Override
	public PageInfo<Role> queryPage(PageParameter pageParameter, Role role) {
		PageHelper.startPage(pageParameter.getPage(), pageParameter.getRows());
		List<Role> roleList = this.list(new QueryWrapper<>(role));
		PageInfo<Role> pageInfo = new PageInfo<>(roleList);
		return pageInfo;
	}

	@Override
	public Boolean insert(User sessionUser, Role role) {
		if(ObjectUtils.allNotNull(sessionUser)){
			role.setCreateUserId(sessionUser.getUserId());
			role.setCreateUsername(sessionUser.getUsername());
		}
		return this.save(role);
	}

	@Override
	public Boolean update(User sessionUser, Role role) {
		if(ObjectUtils.allNotNull(sessionUser)){
			role.setModifyUserId(sessionUser.getUserId());
			role.setModifyUsername(sessionUser.getUsername());
		}
		//添加的时候，有的信息不应该能改动
		Role oldRole = this.getById(role.getRoleId());
		role.setCreateUsername(oldRole.getCreateUsername());
		role.setCreateUserId(oldRole.getCreateUserId());
		role.setCreateDate(oldRole.getCreateDate());
		return this.updateById(role);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Boolean delete(String roleId) {
		//删除主表
		this.removeById(roleId);
		//删除关联表条件base_user_relation category =1 object_id=roleId
		userRelationService.remove(new QueryWrapper<UserRelation>().eq("category", "1").eq("object_id",roleId));
		//删除角色关联关系条件 base_authorize中 object_type=1  object_id = roleId
		authorizeService.remove(new QueryWrapper<Authorize>().eq("object_type", "1").eq("object_id", roleId));
		return null;
	}
}
